<?php
use app\index\model\Arctype;
use app\index\model\Archive;
use app\index\model\Config;
use app\index\model\Flink;
use app\index\model\Banner;
use app\index\model\Tags;
use app\index\model\Order;
use app\index\model\Project;
use app\index\model\Notice;
use app\index\model\Member;
use app\index\model\Comnotice;
use sms\Rest;
include_once("../../extend/sms/Rest.php");


/**
 * @Title: ajaxReturn
 * @Description: todo(ajax提交返回状态信息)
 * @param string $info
 * @param url $url
 * @param string $status
 */
function ajaxReturn($info='', $url='', $status='', $data = ''){
    if(!empty($url)){   //操作成功
        $result = array( 'info' => '操作成功', 'status' => 200, 'url' => $url, );
    }else{   //操作失败
        $result = array( 'info' => '操作失败', 'status' => 0, 'url' => '', );
    }
    if(!empty($info)){$result['msg'] = $info;}
    if(!empty($status)){$result['status'] = $status;}
    if(!empty($data)){$result['data'] = $data;}
    echo json_encode($result);
    exit();
}


/**
 * @Title: channeldata
 * @Description: todo(当前ID的平级栏目)
 * @param int $pid 上级栏目ID
 * @return array
 * @throws
 */
function channeldata($pid){
    $arctype = new Arctype();
    return $arctype->channeldata($pid);
}

/**
 * @Title: channel
 * @Description: todo(直接输出导航链接)
 * @param int $pid 上级栏目ID
 * @param int $nowid 当前显示ID
 * @param string $ishome 是否显示首页
 * @param string $leftlabel 左标签
 * @param string $rightlabel 右标签
 * @param string $class 类名
 * @return string
 * @throws
 */
function channel($pid, $nowid='', $ishome='', $leftlabel="", $rightlabel="", $class=""){
    $arctype = new Arctype();
    return $arctype->channel($pid, $nowid, $ishome, $leftlabel, $rightlabel, $class);
}

/**
 * @Title: arctypefield
 * @Description: todo(指定查询栏目键值)
 * @param int $id 栏目ID
 * @param string $key 查询键值
 * @throws
 */
function arctypefield($id, $key){
    $arctype = new Arctype();
    return $arctype->arctypefield($id, $key);
}

/**
 * @Title: typename
 * @Description: todo(栏目名称)
 * @param int $id 栏目ID
 * @throws
 */
function typename($id){
    $arctype = new Arctype();
    return $arctype->typename($id);
}

/**
 * @Title: typelink
 * @Description: todo(栏目完整链接)
 * @param int $id 栏目ID
 * @throws
 */
function typelink($id){
    $arctype = new Arctype();
    return $arctype->typelink($id);
}

/**
 * @Title: toparctypedata
 * @Description: todo(返回当前栏目的顶级栏目数据)
 * @param int $id
 * @throws
 */
function toparctypedata($id){
    $arctype = new Arctype();
    return $arctype->topArctypeData($id);
}

/**
 * @Title: position
 * @Description: todo(当前位置)
 * @param int $id
 * @param string $home
 * @param string $line
 * @return string
 * @throws
 */
function position($id, $home="首页", $line=">"){
    $arctype = new Arctype();
    return $arctype->position($id, $home, $line);
}

/**
 * @Title: arclist
 * @Description: todo(查询栏目下的文章)
 * @param int $typeid 栏目ID（当前栏目下的所有[无限级]栏目ID）
 * @param int $limit 查询数量
 * @param string $flag 推荐[c] 特荐[a] 头条[h] 滚动[s] 图片[p] 跳转[j]
 * @param string $order 排序
 * @return array
 * @throws
 */
function arclist($typeid='0', $limit='', $flag='', $order='id DESC'){
    $archive = new Archive();
    return $archive->arclist($typeid, $limit, $flag, $order);
}

/**
 * @Title: prenext
 * @Description: todo(上一篇、下一篇)
 * @param array $archiveArr 当前文档数组
 * @return string
 * @throws
 */
function prenext($archiveArr){
    $archive = new Archive();
    return $archive->prenext($archiveArr);
}

/**
 * @Title: click
 * @Description: todo(文档点击数+1)
 * @param array $archiveArr 当前文档数组
 * @throws
 */
function click($archiveArr){
    $archive = new Archive();
    $archive->click($archiveArr);
}

/**
 * @Title: confv
 * @Description: todo(获取配置值)
 * @param string $k
 * @param string $type
 * @return string
 * @throws
 */
function confv($k, $type = 'web'){
    $config = new Config();
    return $config->confv($k, $type);
}

function flinks($mid){
    $flink = new Flink();
    $Flist = $flink->where('status = 1 and mid = '.$mid)->order('sorts asc')->select();
    return $Flist;
}

/**
 * @Title: banners
 * @Description: todo(banner模块数据)
 * @param int $mid
 * @param string $limit
 * @throws
 */
function banners($mid, $limit=''){
    $banner = new Banner();
    return $banner->banners($mid, $limit);
}

/**
 * @Title: Pstatus
 * @Description: todo(项目状态)
 * @return array
 * @throws
 */
function Pstatus(){
    return [
        '0' => '待审核',
        '1' => '预热中',
        '2' => '认投中',
        '3' => '已成功',
        '4' => '待还款',
        '5' => '待兑付',
        '6' => '已兑付',
        '7' => '全部',
        '-1' => '已失败',
        '-2' => '已拒绝'
    ];
}

/**
 * 计算剩余天时分。
 * $unixEndTime string 终止日期的Unix时间
 * @author tangxinzhuan
 * @version 2016-10-28
 */
function OverTime($unixEndTime=0)
{
    if ($unixEndTime <= time()) { // 如果过了活动终止日期
        return '0天0时0分';
    }
    // 使用当前日期时间到活动截至日期时间的毫秒数来计算剩余天时分
    $time = $unixEndTime - time();

    $days = 0;
    if ($time >= 86400) { // 如果大于1天
        $days = (int)($time / 86400);
        $time = $time % 86400; // 计算天后剩余的毫秒数
    }
    return $days.'天';
}

/*
* 转换项目标签
*/
function Gettags($tags){
    $str = '';
    $tModel = new Tags();
    $array = unserialize($tags);
    if(empty($array)){
        return $str;
    }
    foreach($array as $val){
        $str .= '<span>'.$tModel->TagName($val).'</span>';
    }
    return $str;
}
/*
* 首页 - 新闻栏目
*/
function GetCategory(){
    $tModel = new Arctype();
    $aModel = new Archive();
    $CateList = $tModel->where('status=1')->order('sorts asc,id asc')->select();
    foreach($CateList as &$cate){
        $cate['list'] = $aModel->where('status=1 and typeid='.$cate['id'])->order('update_time desc,click desc')->limit(3)->select();
    }
    unset($cate);
    return $CateList;
}

/*
	验证用户登录
*/
function CheckMemberLogin(){
    $userId = session('UID');
    if(empty($userId)){
        return false;
    }else{
        return $userId;
    }
}

/*
	验证企业登录
*/
function CheckComLogin(){
    $CID = session('CID');
    if(empty($CID)){
        return false;
    }else{
        return $CID;
    }
}

/*
	发送短信 - 云片网
*/
function SmsSend($mobile,$code){

    $username='454922379';
    $password='6DDD9161A1FAD476E4310CC347A80C24';
    $gwid='6afc67b5';
    $message = "【好融艺】您的验证码为".$code;
    $curl="http://jk.smstcby.com/smsUTF8.aspx?type=send&username=".$username."&password=".$password."&gwid=".$gwid."&mobile=".$mobile."&message=".$message."&rece=json";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $curl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //https请求 不验证证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //https请求 不验证HOST
    $json_data = curl_exec($ch);
    curl_close($ch);
    $array = json_decode($json_data, true);
    if($array['code']!=0){
        $array['msg'] = $array['remark'];
    }
    return $array;
}

//隐藏手机号
function getXXtel($mobile){
    $pattern = "/(\d{3})\d{4}(\d{4})/";
    $replacement = "\$1****\$2";
    return preg_replace($pattern, $replacement, $mobile);
}

function get_sex($idcard) {
    if(empty($idcard)) return null;
    $sexint = (int) substr($idcard, 16, 1);
    return $sexint % 2 === 0 ? '女' : '男';
}

function get_age($idcard){
    if(empty($idcard)) return null;
    #  获得出生年月日的时间戳
    $date = strtotime(substr($idcard,6,8));
    #  获得今日的时间戳
    $today = strtotime('today');
    #  得到两个日期相差的大体年数
    $diff = floor(($today-$date)/86400/365);
    #  strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
    $age = strtotime(substr($idcard,6,8).' +'.$diff.'years')>$today?($diff+1):$diff;
    return $age;
}

function PutPrivateNumber($idnumber){
    return substr($idnumber,0,5).'******'.substr($idnumber,-4,4);
}

/**
 * 生成订单号
 * @param string $lenth 长度
 * @return string 字符串
 */
function create_order()
{
    return random(12, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ').time();
}
/*
*
*@ 随机生成字符串
*/
function random($length, $chars = '0123456789')
{
    $hash = '';
    $max = strlen($chars) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

//生成邀请码
function Getinvite(){
    $Model = new Member();
    $invite = random(6, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
    $exists = $Model->where(['invite'=>$invite])->find();
    if(empty($exists)){
        return $invite;
    }else{
        Getinvite();
    }
}

/**
 *数字金额转换成中文大写金额的函数
 *String Int $num 要转换的小写数字或小写字符串
 *return 大写字母
 *小数位为两位
 **/
function num_to_rmb($num){
    $c1 = "零壹贰叁肆伍陆柒捌玖";
    $c2 = "分角元拾佰仟万拾佰仟亿";
    //精确到分后面就不要了，所以只留两个小数位
    $num = round($num, 2);
    //将数字转化为整数
    $num = $num * 100;
    if (strlen($num) > 10) {
        return false;
    }
    $i = 0;
    $c = "";
    while (1) {
        if ($i == 0) {
            //获取最后一位数字
            $n = substr($num, strlen($num)-1, 1);
        } else {
            $n = $num % 10;
        }
        //每次将最后一位数字转化为中文
        $p1 = substr($c1, 3 * $n, 3);
        $p2 = substr($c2, 3 * $i, 3);
        if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
            $c = $p1 . $p2 . $c;
        } else {
            $c = $p1 . $c;
        }
        $i = $i + 1;
        //去掉数字最后一位了
        $num = $num / 10;
        $num = (int)$num;
        //结束循环
        if ($num == 0) {
            break;
        }
    }
    $j = 0;
    $slen = strlen($c);
    while ($j < $slen) {
        //utf8一个汉字相当3个字符
        $m = substr($c, $j, 6);
        //处理数字中很多0的情况,每次循环去掉一个汉字“零”
        if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
            $left = substr($c, 0, $j);
            $right = substr($c, $j + 3);
            $c = $left . $right;
            $j = $j-3;
            $slen = $slen-3;
        }
        $j = $j + 3;
    }
    //这个是为了去掉类似23.0中最后一个“零”字
    if (substr($c, strlen($c)-3, 3) == '零') {
        $c = substr($c, 0, strlen($c)-3);
    }
    //将处理的汉字加上“整”
    if (empty($c)) {
        return "零元整";
    }else{
        return $c . "整";
    }
}

//项目进度
function GetProjectBar($id,$type=''){
    $orModel = new Order();
    $Bar = $orModel->where(['project_id'=>$id,'status'=>2,'type'=>1])->sum('money');
    $Bar = $Bar ? $Bar : 0;
    $pModel = new Project();
    $data = $pModel->where(['id'=>$id])->field('target_code,basic_code')->find()->toArray();
    //$Total = $pModel->where(['id'=>$id])->value('target_code,basic_code');
    $Total=$data['target_code'];
    $Bar=$Bar+$data['basic_code'];
    if(!$type){
        return $Bar;
    }
    return round($Bar/$Total*100,2).'%';
}

//通知信息
function TobeNotice($title,$content){
    $Model = new Notice();
    $data = [
        'uid' => session('UID'),
        'create_time' => time(),
        'title' => $title,
        'content' => $content
    ];
    $Model->insert($data);
}

//通知信息
function TobeNotice2($user_id,$title,$content){
    $Model = new Notice();
    $data = [
        'uid' => $user_id,
        'create_time' => time(),
        'title' => $title,
        'content' => $content
    ];
    $Model->insert($data);
}


function getXXname($name){
    $len = mb_strlen($name);
    $str1 = mb_substr($name,0,1);
    $str2 = str_repeat('*',$len-1);
    return $str1.$str2;
}
/**
 *前台企业资料下载
 * @author hey_heyang(635870453@qq.com)
 */
 function QyDataDownLoad($param,$user_info){
    $file_lj = str_replace("\\","/",ROOT_PATH.'public');
    $file_dir = $file_lj . '/' . 'uploads' . '/projectuser/' .$user_info['id'].'/'.$param['fileName'];    // 下载文件存放目录

    if (! file_exists($file_dir) ) {
        die('文件未找到');
    }else{
        // 打开文件
        $file1 = fopen($file_dir, "r");
        // 输入文件标签
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length:".filesize($file_dir));
        Header("Content-Disposition: attachment;filename=" . $param['fileName']);
        ob_clean();
        flush();
        echo fread($file1, filesize($file_dir));
        fclose($file1);
        exit();
    }
}
